package br.com.mtg.movethegarbage.game;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import android.util.Log;
import br.com.mtg.movethegarbage.framework.Game;

public class ScoreList
{
	DataOutputStream dataOutput;
	DataInputStream dataInput;
	Game game;

	public ScoreList(Game _game)
	{
		game = _game;
		dataOutput = null;
		dataInput = null;
	}

	public Score[] getScoreArray(String levelName)
	{
		try
		{
			dataInput = new DataInputStream(game.getFileIO().readFile(levelName + ".mtg"));
		}
		catch (Exception e)
		{
			Log.e("ScoreList", "Error opening score file list from " + levelName);
			return null;
		}

		ArrayList<Score> scoreArrayList = new ArrayList<Score>();
		boolean EOF = false;
		int points = 0;
		String name = "";
		byte[] buffer = new byte[10];
		while (!EOF)
		{
			try
			{
				points = dataInput.readInt();
				dataInput.read(buffer, 0, 10);
				name = new String(buffer);

				scoreArrayList.add(new Score(points, name));
			}
			catch (EOFException e1)
			{
				EOF = true;
			}
			catch (IOException e2)
			{
				Log.e("ScoreList", "Error reading score file list from " + levelName);
			}
		}
		try
		{
			dataInput.close();
		}
		catch (IOException e)
		{
			Log.e("ScoreList", "Error closing score file list from " + levelName);
		}
		if(scoreArrayList.size() == 0)return null;
		dataInput = null;
		Score[] scoreArray = new Score[scoreArrayList.size()];
		for(int i = 0; i < scoreArrayList.size(); i++)
		{
			scoreArray[i] = scoreArrayList.get(i);
		}
		Arrays.sort(scoreArray, new Comparator<Score>() {

			public int compare(Score score1, Score score2)
			{
				return (score1.points < score2.points ? -1 : (score1.points > score2.points ? +1 : 0));
			}
		});
		return scoreArray;
	}

	public void writeScore(Score score, String levelName)
	{
		try
		{
			dataOutput = new DataOutputStream(game.getFileIO().writeFile(levelName + ".mtg", true));
			dataOutput.writeInt(score.points);
			dataOutput.writeBytes(score.name);
			dataOutput.close();
			dataOutput = null;
		}
		catch (Exception e)
		{
			Log.e("ScoreList", "Error opening/writing score file list from " + levelName);
		}
	}
}